package com.yilin.tms.order.controller;

import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.commons.util.StringUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.application.ReturnData;
import com.yilin.tms.core.commons.annotation.*;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.commons.utils.UserUtil;
import com.yilin.tms.core.commons.base.BaseController;
import com.yilin.tms.core.commons.model.AuthData;
import com.yilin.tms.core.entity.order.goods.GoodsOrder;
import com.yilin.tms.core.entity.order.payment.OrderPaymentCost;
import com.yilin.tms.core.entity.user.OrganType;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.organize.MemberType;
import com.yilin.tms.order.service.owner.IGoodsOwnerService;
import com.yilin.tms.order.service.order.IGoodsService;
import com.yilin.tms.order.service.payment.IOrderPaymentCostService;
import com.yilin.tms.core.remote.IUserRemote;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 货单控制器
 *
 * @author zhangjinyuan
 * @date 2022/10/29
 */
@RestController
@RequestMapping("/order/goods/")
public class GoodsController extends BaseController {

    @Resource
    IGoodsService goodsService;
    @Resource
    IGoodsOwnerService goodsOwnerService;
    @Resource
    IOrderPaymentCostService orderPaymentCostService;

    @Resource
    IUserRemote userRemote;


    /**
     * 获取货源分页
     * 排序时sort!=null，筛选时query!=null，按离我最近排序时position!=null
     */
    @PostMapping(value = "getGoodsOrderPage")
    @NotNull({"page", "limit"})
    public ReturnData<PageData<GoodsOrder>> getGoodsOrderPage(GoodsOrder query, @Explain("页码") Integer page, @Explain("条数") Integer limit) {
        PageData<GoodsOrder> pageData = goodsService.getGoodsOrderPage(getLoginUser(), query, page, limit);
        return jsonView(true, "获取货源列表成功", pageData);
    }

    /**
     * 获取货源详情
     */
    @PostMapping(value = "getGoodsOrderDetail")
    @NotNull("goodsOrderId")
    public ReturnData<GoodsOrder> getGoodsOrderDetail(@Explain("货源ID") String goodsOrderId) {
        GoodsOrder goodsOrder = goodsService.getGoodsOrderDetail(getLoginUser(), goodsOrderId);
        return jsonView(true, "获取货源详情成功", goodsOrder);
    }

    /**
     * 根据ID获取货源
     */
    @PostMapping(value = "getGoodsOrderById")
    @NotNull("goodsOrderId")
    public ReturnData<GoodsOrder> getGoodsOrderById(@Explain("货源ID") String goodsOrderId) {
        GoodsOrder goodsOrder = goodsService.getById(goodsOrderId);
        return jsonView(true, "获取货源详情成功", goodsOrder);
    }

    /**
     * 根据货单号获取货源
     */
    @PostMapping(value = "getGoodsOrderByNo")
    @NotNull("goodsOrderNo")
    public ReturnData<GoodsOrder> getGoodsOrderByNo(@Explain("货源单号") String goodsOrderNo) {
        GoodsOrder goodsOrder = goodsService.getGoodsOrderByNo(goodsOrderNo);
        return jsonView(true, "获取货源详情成功", goodsOrder);
    }

    /**
     * 获取货源分页 隐藏敏感信息
     */
    @PostMapping(value = "getPublicGoodsOrderPage")
    @SkipLoginVerify
    @NotNull({"page", "limit"})
    public ReturnData<PageData<GoodsOrder>> getPublicGoodsOrderPage(GoodsOrder query, @Explain("页码") Integer page, @Explain("条数") Integer limit) {
        PageData<GoodsOrder> pageData = goodsService.getPublicGoodsOrderPage(query, page, limit);
        return jsonView(true, "获取货源列表成功", pageData);
    }

    /**
     * 保存货源
     */
    @ApiInterceptor
    @PostMapping(value = "saveGoodsOrder")
    @NotNull({ "priceMode", "settlementType", "shipperTransportCost", "shipperServiceCost",
            "shipperTaxCost", "shipperTotalCost", "goodsOrderNoteList", "fullLoad",
            "autoDelivery", "autoAudit", "matching", "includedTax", "skipNeedReceipt", "startFence", "noBargain",
            "handLiquidation", "needUploadShipping", "needUploadShipping", "skipConfirmReceipt", "needUploadReceipt",
            "transportTypeName", "transportTypeCode"})
    @UserTarget(UserType.shipperUser)
    public ReturnData<Object> saveGoodsOrder(GoodsOrder goodsOrder) {
        if (goodsOrder.getGoodsStatus() == null ) goodsOrder.setGoodsStatus(GoodsOrder.GoodsStatus.save);
        if (!ArrayUtil.initList(GoodsOrder.GoodsStatus.save,GoodsOrder.GoodsStatus.template).contains(goodsOrder.getGoodsStatus())){
            return jsonView(false, "货源状态指定错误");
        }
        if (StringUtil.isNotEmpty(goodsOrder.getTruckTypeIds()) && StringUtil.isEmpty(goodsOrder.getTruckTypeNames())) {
            return jsonView(false, "需求车型名称不能为空");
        }
        if (goodsOrder.getPriceMode() == GoodsOrder.PriceMode.wholePrice) {
            if (goodsOrder.getSettlementType() != GoodsOrder.SettlementType.releasePricing) return jsonErrView("整单必须为一口价结算");
            if (!goodsOrder.getNoBargain()) return jsonView(false, "整单计价货源不能议价");
        }
        if (goodsOrder.getPriceMode() == GoodsOrder.PriceMode.unitPrice) {
            if (goodsOrder.getSettlementType() == GoodsOrder.SettlementType.gatherTotal) return jsonErrView("单价计价货源不能汇总结算");
        }
        if (goodsOrder.getPriceMode() == GoodsOrder.PriceMode.notPrice){
            if ( goodsOrder.getSettlementType() != GoodsOrder.SettlementType.gatherTotal)  return jsonErrView("汇总计价货源只能选择汇总结算");
        }
        if (!goodsOrder.getNoBargain()) {
            MemberType shipperMemberType = ParamUtil.isSuccess(userRemote.getMyMemberTypeByOrganizeId(getLoginUser().getOrganizeId()));
            if (shipperMemberType.getReleasePaymentRate() != 0D) return jsonErrView("您需要发布付款，不支持议价模式");
        }
        //检查货主基本信息认证是否完善
        List<AuthData.AuthItem> itemList = ArrayUtil.initList(AuthData.AuthItem.authIdCard);
        if (getLoginUser().getOrganType()!= OrganType.individual) itemList.add(AuthData.AuthItem.authBusinessLicense);
        ParamUtil.isSuccess(userRemote.checkAuthStatus(null,itemList.toArray(new AuthData.AuthItem[0])));
        //使用会员配置继续检查货源发布权限
        goodsOrder.setShipperAccountId(getLoginUser().getId());
        goodsOwnerService.checkGoodsRelease(goodsOrder);
        goodsOrder = goodsService.saveGoodsOrder(getLoginUser(), goodsOrder);
        return jsonView(SUCCESS_CODE, "保存货源成功", goodsOrder.getId());
    }

    /**
     * 推送货源
     */
    @PostMapping(value = "pushGoodOrderToTrucker")
    @NotNull({"goodsOrderId", "truckerAccountId"})
    @UserTarget(UserType.shipperUser)
    public ReturnData<Object> pushGoodOrderToTrucker(@Explain("货源ID") String goodsOrderId, @Explain("车主ID") String truckerAccountId) {
        GoodsOrder goodsOrder = goodsService.getById(goodsOrderId);
        ParamUtil.isNull(goodsOrder, "未查询到该货源");
        ParamUtil.notEquals("只能推送已上线的货源", goodsOrder.getGoodsStatus(), GoodsOrder.GoodsStatus.release);
        ParamUtil.notEquals("不是你的货源无权操作", getLoginUser().getId(), goodsOrder.getShipperAccountId());
        Account truckerAccount = ParamUtil.isSuccess(userRemote.getAccountById(truckerAccountId));
        ParamUtil.isNull(truckerAccount, "未查询到推送车主信息");
        ParamUtil.notEquals("该用户不是车主", truckerAccount.getUserType(), UserType.truckerUser);
        ReturnData<String> returnData = goodsOwnerService.robVehicleTypeMatching(truckerAccount.getOrganizeId(), goodsOrder);
        if (!returnData.isSuccess()) return jsonView(false, "该车主拥有车型不符合货源要求");
        goodsService.pushGoodOrderToTrucker(getLoginUser(), goodsOrder, truckerAccount);
        return jsonView(true, "推送成功");
    }

    /**
     * 货源上线
     */
    @PostMapping(value = "releaseGoodsOder")
    @NotNull("goodsOrderId")
    @UserTarget({UserType.shipperUser, UserType.platformUser})
    public ReturnData<Object> releaseGoodsOder(@Explain("货源ID") String goodsOrderId, String endTime) {
        GoodsOrder goodsOrder = goodsService.getGoodsOrderDetail(getLoginUser(),goodsOrderId);
        ParamUtil.isNull(goodsOrder, "未知的货源");
        // 3# 检查认证状态
        List<AuthData.AuthItem> itemList = ArrayUtil.initList(AuthData.AuthItem.authIdCard);
        if (getLoginUser().getOrganType()!= OrganType.individual) itemList.add(AuthData.AuthItem.authBusinessLicense);
        ParamUtil.isSuccess(userRemote.checkAuthStatus(null,itemList.toArray(new AuthData.AuthItem[0])));
        ParamUtil.notEquals("当前货源状态不能发布", goodsOrder.getGoodsStatus(), GoodsOrder.GoodsStatus.save, GoodsOrder.GoodsStatus.reserve);
        if (getLoginUser().getUserType() == UserType.platformUser) {
            ParamUtil.equals("平台用户不能上线整单计价的货源", goodsOrder.getPriceMode(), GoodsOrder.PriceMode.wholePrice);
        }
        if (getLoginUser().getUserType() == UserType.shipperUser) {
            ParamUtil.notEquals("不是你的货源不能操作", goodsOrder.getShipperAccountId(), getLoginUser().getId());
        }
        if (StringUtil.isNotEmpty( endTime )) {
            Date date = DateTimeUtil.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss");
            goodsOrder.setEndTime(DateTimeUtil.maxDate(date));
            if (goodsOrder.getEndTime().getTime() <= System.currentTimeMillis()) {
                return jsonView(false, "截至时间不能小于当前时间");
            }
        }
        //检查支付状态
        OrderPaymentCost paymentCost = orderPaymentCostService.generateGoodsOrderPayment(goodsOrder);
        if (paymentCost.getPayStatus() == OrderPaymentCost.PayStatus.create) return jsonErrView("请先支付货单！");
        if (paymentCost.getPayStatus() == OrderPaymentCost.PayStatus.wait) return jsonErrView("请等待货单支付结果！");
        goodsService.releaseGoodsOrder(getLoginUser(), goodsOrder);
        return jsonView(SUCCESS_CODE, "上线成功");
    }

    /**
     * 货源预约上线
     */
    @PostMapping(value = "reserveGoodsOder")
    @NotNull("goodsOrderId")
    @UserTarget({UserType.shipperUser, UserType.platformUser})
    public ReturnData<Object> reserveGoodsOder(@Explain("货源ID") String goodsOrderId, String reserveTime, String endTime) {
        return jsonView(SUCCESS_CODE, "货源上线成功");
    }

    /**
     * 货源下线
     */
    @PostMapping(value = "recallGoodsOder")
    @NotNull("goodsOrderId")
    @UserTarget({UserType.shipperUser, UserType.platformUser})
    public ReturnData<Object> recallGoodsOder(@Explain("货源ID") String goodsOrderId) {
        GoodsOrder goodsOrder = goodsService.getById(goodsOrderId);
        ParamUtil.isNull(goodsOrder, "未知的货源");
        if (getLoginUser().getUserType() == UserType.shipperUser) {
            ParamUtil.notEquals("不是你的货源不能操作", goodsOrder.getShipperAccountId(), getLoginUser().getId());
        }
        ParamUtil.notEquals("只有上线的货源才能下线", goodsOrder.getGoodsStatus(), GoodsOrder.GoodsStatus.release);
        goodsService.recallGoodsOrder(getLoginUser(), goodsOrder);
        return jsonView(SUCCESS_CODE, "货源下线成功");
    }


    /**
     * 货源作废
     */
    @PostMapping(value = "scrapGoodsOder")
    @NotNull({"goodsOrderId"})
    @UserTarget({UserType.shipperUser, UserType.platformUser})
    public ReturnData<Object> scrapGoodsOder(@Explain("货源ID") String goodsOrderId) {
        GoodsOrder goodsOrder = goodsService.getById(goodsOrderId);
        if (goodsOrder.getGoodsStatus() == GoodsOrder.GoodsStatus.scrap) return jsonErrView("货源已作废");
        goodsService.scrapGoodsOder(getLoginUser(), goodsOrder);
        return jsonView(SUCCESS_CODE,"作废成功");
    }

    /**
     * 货源移除
     * 只能删除已作废的货单
     */
    @PostMapping(value = "deleteGoodsOder")
    @NotNull({"goodsOrderId"})
    @UserTarget({UserType.shipperUser, UserType.platformUser})
    public ReturnData<Object> deleteGoodsOder(@Explain("货源ID数组") String[] goodsOrderId) {
        GoodsOrder goodsOrder = goodsService.getById(goodsOrderId);
        if (getLoginUser().getUserType() == UserType.shipperUser) {
            ParamUtil.notEquals("不是你的货源不能删除", goodsOrder.getShipperAccountId(), getLoginUser().getId());
        }
        if (goodsOrder.getGoodsStatus() != GoodsOrder.GoodsStatus.scrap) return jsonErrView("请先作废货源");
        goodsService.deleteGoodsOrder(getLoginUser(), goodsOrder);
        return jsonView(SUCCESS_CODE, "删除成功");
    }

    /**
     * 获取货源运输状态
     *
     * @param goodsOrderNo 货单号，多个货单","隔开
     * @return HashMap<货单号, 是否完成运输>
     */
    @PostMapping(value = "orderTransportState")
    @NotNull("goodsOrderNo")
    public ReturnData<HashMap<String, Boolean>> orderTransportState(@Explain("货源单号") String goodsOrderNo) {
        HashMap<String, Boolean> map = goodsService.orderTransportState(goodsOrderNo);
        return jsonView(true, "获取成功", map);
    }

    /**
     * 通过WMS生成货源并分配
     */
    @PostMapping(value = "wmsSaveGoodsOrder")
    @NotNull({"goodsOrderType", "priceMode", "settlementType", "shipperTransportCost", "shipperServiceCost",
            "shipperTaxCost", "shipperTotalCost", "goodsConsignorNoteList", "goodsConsigneeNoteList", "fullLoad",
            "autoDelivery", "autoAudit", "matching", "includedTax", "skipNeedReceipt", "startFence", "noBargain",
            "handLiquidation", "needUploadShipping", "needUploadShipping", "skipConfirmReceipt", "needUploadReceipt",
            "robOrganizeId"})
    public ReturnData<String> wmsSaveGoodsOrder(GoodsOrder goodsOrder) {
        Account loginUser = UserUtil.getLoginUser(request);
        String goodsOrderNo = goodsService.wmsSaveGoodsOrder(loginUser, goodsOrder);
        return jsonView(true, "生成成功", goodsOrderNo);
    }

    /**
//     * 根据组织ID查询已经上线的货源
//     */
//    @PostMapping(value = "getGoodsOrderByOrganizeId")
//    @NotNull("organizeId")
//    @SkipLoginVerify
//    public ReturnData<List<GoodsOrder>> getGoodsOrderByOrganizeId(@Explain("组织ID") String organizeId) {
//        List<GoodsOrder> goodsOrderList = goodsService.getGoodsOrderByOrganizeId(organizeId);
//        return jsonView(true, "获取抢单成功", goodsOrderList);
//    }
//
//    /**
//     * 根据用户ID查询已经上线的货源
//     */
//    @PostMapping(value = "getGoodsOrderByAccountId")
//    @NotNull("accountId")
//    @SkipLoginVerify
//    public ReturnData<List<GoodsOrder>> getGoodsOrderByAccountId(@Explain("组织ID") String accountId) {
//        List<GoodsOrder> goodsOrderList = goodsService.getGoodsOrderByAccountId(accountId);
//        return jsonView(true, "获取抢单成功", goodsOrderList);
//    }


}
